package com.wxzz.elearing.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.wxzz.elearing.pay.dto.UserTransactionDto;
import com.wxzz.elearing.pay.entity.UserOrder;
import com.wxzz.elearing.pay.entity.UserTransaction;
import com.wxzz.elearing.pay.entity.UserWallet;
import com.wxzz.elearing.pay.mapper.UserOrderMapper;
import com.wxzz.elearing.pay.mapper.UserTransactionMapper;
import com.wxzz.elearing.pay.mapper.UserWalletMapper;
import com.wxzz.elearing.pay.service.IUserTransactionService;
import com.wxzz.elearing.pay.service.IUserWalletService;
import com.wxzz.elearing.pay.service.openfeign.IDocentFeign;
import com.wxzz.elearing.pay.service.openfeign.IEnterpriseFeign;
import com.wxzz.elearing.pay.service.openfeign.IWxUserApiFeign;
import com.wxzz.elearning.common.aop.Idempotent;
import com.wxzz.elearning.common.dto.FeignEnterpriseDto;
import com.wxzz.elearning.common.dto.FeignWxUserDto;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.utils.OpenFeignUtil;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.rmi.ServerException;
import java.util.List;
import java.util.Optional;
import java.util.function.IntFunction;

/**
 * <p>
 * 余额明细 服务实现类
 * </p>
 *
 * @author
 * @since 2021-04-23
 */
@Service

public class UserTransactionServiceImpl extends ServiceImpl<UserTransactionMapper, UserTransaction> implements IUserTransactionService {

    private static final Logger logger = LoggerFactory.getLogger(UserTransactionServiceImpl.class);

    @Autowired
    private UserTransactionMapper userTransactionMapper;

    @Autowired
    private IEnterpriseFeign enterpriseFeign;

    @Autowired
    private IWxUserApiFeign wxUserApiFeign;

    @Autowired
    private IDocentFeign docentFeign;

    @Transactional
    @Override
    public ReturnVO<JgPageVo<List<UserTransaction>>> listUserTransaction(JSONObject jsonObject, UserTransactionDto userTransactionDto) {
        PageHelper.startPage(userTransactionDto.getCurPage(), userTransactionDto.getMaxPage());
        QueryWrapper<UserTransaction> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        if (userTransactionDto.getUserType() != null) {
            queryWrapper.eq("user_type", userTransactionDto.getUserType());
        }
        //平台
        if (userTransactionDto.getUserType() != null && userTransactionDto.getUserType() == 0) {
            queryWrapper.eq("user_id", 0);
        }
        //企业
        if (userTransactionDto.getUserType() != null && userTransactionDto.getUserType() == 1) {
            queryWrapper.eq("user_id", jsonObject.getLong("enterpriseId"));
        }
        //用户
        if (userTransactionDto.getUserType() != null && userTransactionDto.getUserType() == 2) {
            queryWrapper.eq("user_id", jsonObject.getLong("id"));
        }
        //讲师
        if (userTransactionDto.getUserType() != null && userTransactionDto.getUserType() == 3) {
            queryWrapper.eq("user_id", jsonObject.getLong("docentId"));
        }
        if (StringUtils.isNotBlank(userTransactionDto.getChangeType())) {
            queryWrapper.like("change_type", userTransactionDto.getChangeType() + "%");
        }
        if (StringUtils.isNotBlank(userTransactionDto.getTransactionStatus())) {
            queryWrapper.like("transaction_status", userTransactionDto.getTransactionStatus() + "%");
        }
        if (StringUtils.isNotBlank(userTransactionDto.getUsername())) {
            queryWrapper.like("username", userTransactionDto.getUsername());
        }
        if (userTransactionDto.getType() != null) {
            queryWrapper.eq("type", userTransactionDto.getType());
        }
        List<UserTransaction> userTransactions = userTransactionMapper.selectList(queryWrapper);
        return new ReturnVO<>("余额变动查询成功", new JgPageVo<>(new PageInfo(userTransactions)));
    }

    @Override
    public String getUserName(Integer userType, Long userId) {
        String username = "";
        if (userType == 0) {
            username = "平台";
        }
        if (userType == 1) {
            FeignEnterpriseDto feignEnterpriseDto = enterpriseFeign.selectEnterpriseDtoById(userId);
            username = feignEnterpriseDto.getEnterpriseName();
        }
        if (userType == 2) {
            FeignWxUserDto feignWxUserDto = wxUserApiFeign.selectFeignWxUserDtoByWxUserId(userId);
            username = feignWxUserDto.getEnterpriseName();
        }
        if (userType == 3) {
            ReturnVO<String> stringReturnVO = docentFeign.selectDocentById(userId);
            JSONObject docent = OpenFeignUtil.getJSONObject(stringReturnVO);
            if (docent != null) {
                username = docent.getString("docentName");
            }
        }
        return username;
    }

    @Autowired
    private UserOrderMapper userOrderMapper;

    @Autowired
    private UserWalletMapper userWalletMapper;

    @Autowired
    private IUserWalletService userWalletService;


    @Idempotent
    @Transactional
    @Override
    public ReturnVO giveAnswers(Long userId, Long orderId) {
        UserOrder userOrder = userOrderMapper.selectById(orderId);
        Optional.ofNullable(userOrder).orElseThrow(() -> new ServiceException("该订单不存在"));
        if (userOrder.getOrderStatus() == 0) {
            throw new ServiceException("该订单为未支付状态");
        }
        UserWallet userWallet = userWalletMapper.selectOne(new LambdaQueryWrapper<UserWallet>()
                .eq(UserWallet::getUserType, 0)
                .eq(UserWallet::getUserId, 0));
        if (userWallet.getUserBalance().compareTo(userOrder.getIncomePrice()) == -1) {
            logger.error("平台钱包余额不足,无法给予赏金,订单对象:[{}],平台钱包对象:[{}]", userOrder.toString(), userWallet.toString());
            throw new ServiceException("平台钱包余额不足,无法给予赏金,请联系管理员");
        }
        //用户钱包
        UserWallet user = userWalletService.updateUserWallet(userId, 2, userOrder.getIncomePrice());
        UserTransaction get = new UserTransaction();
        get.setMoney(userOrder.getIncomePrice());
        get.setBalance(user.getUserBalance());
        get.setDescription("回答获得赏金");
        get.setBusinessRemark("订单编号:" + userOrder.getOrderNum());
        get.setUserType(2);
        get.setType(2);
        get.setUserId(userId);
        get.setUsername(getUserName(2, userId));
        get.setTransactionStatus("存入余额");
        get.setChangeType("回答获得赏金");
        userTransactionMapper.insert(get);
        //平台钱包
        UserWallet platform = userWalletService.updateUserWallet(0L, 0, userOrder.getIncomePrice().negate());
        UserTransaction put = new UserTransaction();
        put.setMoney(userOrder.getIncomePrice().negate());
        put.setBalance(platform.getUserBalance());
        put.setDescription("给予用户赏金");
        put.setBusinessRemark("订单编号:" + userOrder.getOrderNum());
        put.setUserType(0);
        put.setType(2);
        put.setUserId(0L);
        put.setUsername(getUserName(0, 0L));
        put.setTransactionStatus("给予用户赏金");
        put.setChangeType("给予用户赏金");
        userTransactionMapper.insert(put);
        return new ReturnVO("赏金给予成功", orderId);
    }

}
